namespace ScreenUp
{
    using System;
    using System.Diagnostics;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    internal class InterceptKeys
    {
        private static IntPtr _hookID = IntPtr.Zero;
        private static LowLevelKeyboardProc _proc = new LowLevelKeyboardProc(InterceptKeys.HookCallback);
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x100;

        [DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
        [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
        public static void Hook()
        {
            _hookID = SetHook(_proc);
        }

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if ((nCode >= 0) && (wParam == ((IntPtr) 0x100)))
            {
                switch (((Keys) Marshal.ReadInt32(lParam)))
                {
                    case Keys.Snapshot:
                        Program.f1.Desktop();
                        break;

                    case Keys.Control | Keys.F12:
                        Program.f1.ActiveWindow();
                        break;
                }
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            IntPtr ptr;
            using (Process process = Process.GetCurrentProcess())
            {
                using (ProcessModule module = process.MainModule)
                {
                    ptr = SetWindowsHookEx(13, proc, GetModuleHandle(module.ModuleName), 0);
                }
            }
            return ptr;
        }

        [DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
        public static void UnHook()
        {
            UnhookWindowsHookEx(_hookID);
        }

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    }
}

